package com.cl.blog.web.client;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cl.blog.annotation.Login;
import com.cl.blog.common.Const;
import com.cl.blog.common.Result;
import com.cl.blog.entity.BUser;
import com.cl.blog.service.BUserService;
import com.cl.blog.util.JwtUtil;
import com.cl.blog.util.RedisUtil;
import com.cl.blog.vo.LoginVo;
import com.cl.blog.vo.RegisterVo;
import com.google.code.kaptcha.Producer;
import io.jsonwebtoken.Claims;
import lombok.extern.java.Log;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @Author 付
 * @Date 2024-03-14 18:06
 * @Version 1.0
 * @description
 * @since 1.0
 */

@RestController
@RequestMapping("/user")
public class UserLoginController {

	@Resource
	BUserService bUserService;
	@Resource
	JwtUtil jwtUtil;
	// 导入谷歌验证码工具
	@Resource
	Producer producer;
	@Resource
	RedisUtil redisUtil;

	@PostMapping("/login")
	public Result login(@Validated @RequestBody LoginVo loginVo) {
		System.out.println("获得的数据----" + loginVo);
		Assert.notNull(loginVo, "抱歉，用户名和密码不能为空");
		BUser bUser = bUserService.login(loginVo);

		String token = jwtUtil.generateToken(bUser.getId(), Const.GRADE_USER);
		bUser.setToken(token);
		System.out.println("用户数据--->" + bUser);
		return Result.success(bUser);
	}

	@PostMapping("/register")
	public Result register(@RequestBody LoginVo loginVo) {
		BUser bUser = bUserService.register(loginVo);

		return Result.success(bUser);
	}


	// 生成验证码图片
	@GetMapping("/captcha")
	public Result getCaptcha() throws IOException {
		// 生成uuid
		String uuid = UUID.randomUUID().toString();
		// 生成验证码
		String code = producer.createText();

		System.out.println("uuid=" + uuid + "----" + "code=" + code);
//		生成base64编码的图片验证码
		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", byteArrayOutputStream);

		String base64Img = "data:image/jpeg;base64," + Base64Encoder.encode(byteArrayOutputStream.toByteArray());

		// 把uuid和验证码存储到redis
		redisUtil.setEx(uuid, code, 120, TimeUnit.SECONDS);
		System.out.println("redis获取key---" + redisUtil.get(uuid));
		// 返回uuid和base64编码
		return Result.success(MapUtil.builder().put("uuid", uuid).put("base64Img", base64Img).build());
	}

	/**
	 * 用户注册
	 *
	 * @param registerVo
	 * @return
	 */
	@GetMapping("/register")
	public Result register(@Validated @RequestBody RegisterVo registerVo) {
		System.out.println("/注册的用户信息---" + registerVo);
		// 获取验证码进行判断
		boolean equals = registerVo.getCode().equals(redisUtil.get(registerVo.getUuid()));
		Assert.isTrue(equals, "验证码错误");

		// 判断是否以及存在该用户
		long count = bUserService.count(new QueryWrapper<BUser>().eq("username", registerVo.getUsername()));
		if (count > 0) {
			return Result.error("抱歉，该用户已存在");
		}

		BUser bUser = new BUser();
		bUser.setUsername(registerVo.getUsername());
		bUser.setPassword(SecureUtil.md5(registerVo.getPassword()));
		bUser.setCreateTime(LocalDateTime.now());
		bUser.setIsDelete(0);
		bUser.setIsLogin(0);
		bUser.setNickname(RandomUtil.randomString(RandomUtil.randomInt(8, 12)));

		bUserService.save(bUser);
		return Result.success();
	}

	/**
	 * 用户注销
	 *
	 * @return
	 */
	@GetMapping("/logout")
	@Login
	public Result logout(HttpServletRequest request) {
		String token = request.getHeader("token");
		Claims claim = jwtUtil.getClaimByToken("token", "CLIENT");
		String userId = claim.getSubject();
		bUserService.logout(userId);
		return Result.success();
	}
}
